<template>
  <div class="user-management">
    <!-- 页面头部操作区 -->
    <div class="header-actions">
      <div class="search-container">
        <el-input
          v-model="searchUsername"
          placeholder="请输入用户名搜索"
          clearable
          style="width: 300px"
        >
          <template #append>
            <el-button icon="el-icon-search" @click="handleSearch"></el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <el-table
      v-loading="loading"
      :data="userList"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="用户ID" width="80" align="center" />
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" width="180" />
      <el-table-column prop="avatar" label="用户头像" width="120" align="center">
        <template #default="{ row }">
          <el-image 
            v-if="row.avatar && row.avatar.trim()" 
            :src="row.avatar.trim()" 
            style="width: 40px; height: 40px; border-radius: 50%"
            :preview-src-list="[row.avatar.trim()]"
          />
          <div v-else style="width: 40px; height: 40px; border-radius: 50%; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center">
            <span>{{ row.username ? row.username.charAt(0).toUpperCase() : '?' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginTime" label="最后登录时间" width="200">
        <template #default="{ row }">
          {{ formatDate(row.lastLoginTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="50%"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="100px"
        :rules="formRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.status" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { findUserPage, updateUserStatus } from '../../api/user'

// 响应式数据定义
const userList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchUsername = ref('')

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  username: '',
  email: '',
  phone: '',
  status: 1
})

// 表单验证规则
const formRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) {
    return '--'
  }
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取用户列表
const fetchUserList = async (showLoading = true) => {
  if (showLoading) {
    loading.value = true
  }
  try {
    // 构建分页查询参数
    const pageDTO = {
      current: currentPage.value,
      size: pageSize.value,
      username: searchUsername.value || undefined
    }

    console.log('分页查询参数:', pageDTO)
    const response = await findUserPage(pageDTO)
    console.log('API响应数据:', response)

    if (response.success) {
      let users = Array.isArray(response.data) ? response.data : []
      
      // 根据后端返回的数据结构处理
      if (response.data && response.data.data) {
        users = response.data.data
      }

      // 处理每个用户的状态值，确保是数字 0 或 1
      userList.value = users.map(user => ({
        ...user,
        status: typeof user.status === 'boolean' ? (user.status ? 1 : 0) : Number(user.status)
      }))
      
      // 设置total值，确保分页正确显示
      // 根据后端返回的数据结构，优先使用response.total字段
      if (response.total !== undefined && response.total !== null) {
        total.value = Number(response.total)
      }
      // 其次检查response.data是否有total字段（兼容不同的返回格式）
      else if (response.data && response.data.total !== undefined && response.data.total !== null) {
        total.value = Number(response.data.total)
      }
      // 最后，如果都没有，使用当前数据的数量作为默认值
      else {
        total.value = users.length
      }
      
      console.log('最终设置的total值:', total.value)
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
      // 即使请求失败，也设置一个默认的total值，确保分页组件可见
      total.value = 0
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    // 即使发生异常，也设置一个默认的total值，确保分页组件可见
    total.value = 0
  } finally {
    if (showLoading) {
      loading.value = false
    }
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  searchUsername.value = ''
  currentPage.value = 1
  fetchUserList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUserList()
}

// 页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchUserList()
}

// 状态变更
const handleStatusChange = async (row) => {
  // 保存当前状态，用于出错时恢复
  const originalStatus = row.status
  try {
    // 确保传递给后端的是数字 0 或 1
    // 0 表示禁用，1 表示启用
    const numericStatus = typeof row.status === 'boolean' ? (row.status ? 1 : 0) : Number(row.status)
    
    // 创建符合后端接口要求的DTO对象
    const updateUserStatusDTO = {
      id: row.id,
      status: numericStatus
    }
    await updateUserStatus(updateUserStatusDTO)
    // 更新本地状态为数字值
    row.status = numericStatus
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    // 恢复原状态（确保使用数字值）
    row.status = typeof originalStatus === 'boolean' ? (originalStatus ? 1 : 0) : Number(originalStatus)
  }
}

// 编辑用户
const handleEdit = (row) => {
  // 深拷贝用户数据到编辑表单
  Object.assign(editForm, row)
  editDialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户「${row.username}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    // 这里应该调用删除API
    ElMessage.success('用户删除成功')
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 保存编辑
const handleSave = async () => {
  try {
    await editFormRef.value.validate()
    // 这里应该调用更新API
    ElMessage.success('用户信息更新成功')
    editDialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请检查表单数据')
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  editDialogVisible.value = false
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>